<?php

namespace app\common\model;

use think\Model;

class Agent extends Model
{
    // 表名
    protected $name = 'agent';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    
    // 追加属性
    protected $append = [
        'create_time_text',
        'disabled_time_text',
        'update_time_text',
	    'level_text',
	    'status_text',
    ];
    

    CONST LEVEL_2 = 2;
	const LEVEL_3 = 3;
	const LEVEL_4 = 4;
    
    public static $levelList = [
	    self::LEVEL_2 => '初级代理商',
	    self::LEVEL_3 => '中级代理商',
	    self::LEVEL_4 => '高级代理商'
    ];

	public function getLevelTextAttr($value, $data) {
		$value = $value ? $value : $data['level'];
		$list = self::$levelList;
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	const STATUS_Y = 1;
	const STATUS_D = 0;
	
	public static $statusList = [
		self::STATUS_Y => '正常',
		self::STATUS_D => '禁用'
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDisabledTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['disabled_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setDisabledTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    //关联用户
    public function user(){
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
    
    //关联上级
    public function puser(){
		return $this->belongsTo('user', 'pid', 'id', '', 'left')->setEagerlyType(0);
    }
    
    //关联上上级
    public function ppuser(){
		return $this->belongsTo('user', 'ppid', 'id', '', 'left')->setEagerlyType(0);
    }
    
}
